package ink.xiaobaibai.userDetails;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import ink.xiaobaibai.entity.AdminUser;
import ink.xiaobaibai.service.IAdminUserRoleService;
import ink.xiaobaibai.service.IAdminUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @description: 账号密码登录查询DB类
 * @author: 小白白
 * @create: 2021-05-11
 **/

@Component
@Slf4j
public class UserNumberDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private IAdminUserService adminUserService;

    @Autowired
    private IAdminUserRoleService adminUserRoleService;

    @Override
    public UserDetails loadUserByUsername(String userNumber) throws UsernameNotFoundException {

        QueryWrapper<AdminUser> q1 = new QueryWrapper<>();
        q1.select("id", "user_password");
        q1.eq("user_number", userNumber);
        AdminUser adminUser = this.adminUserService.getOne(q1);
        if (adminUser == null) {
            return null;
        }

        //这里需要联表查询,关联角色表和用户角色对应表,一次性查出对应的多个角色名
        List<String> roleList = this.adminUserRoleService.getRoleByUserId(adminUser.getId());
        if (roleList == null || roleList.size() == 0) {
            log.info("未分配角色的用户:{}", userNumber);
            return null;
        }
        List<SimpleGrantedAuthority> grantedAuthorityList = roleList.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
        return new MyUser(adminUser.getId(), userNumber, adminUser.getUserPassword(), grantedAuthorityList);

    }

    public class MyUser extends User {

        private Integer userId;

        public MyUser(Integer userId, String username, String password, Collection<? extends GrantedAuthority> authorities) {
            super(username, password, true, true, true, true, authorities);
            this.userId = userId;
        }

        public Integer getUserId() {
            return this.userId;
        }
    }

}
